package com.chenxi.vhr.controller.system;

import com.chenxi.vhr.bean.BaseUser;
import com.chenxi.vhr.bean.common.NasDeleteListForm;
import com.chenxi.vhr.bean.common.Result;
import com.chenxi.vhr.bean.form.BaseUserRoleEditForm;
import com.chenxi.vhr.service.BaseUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : zhangchenxi
 * @create : 2022-02-08
 **/
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    BaseUserService userService;

    /**
     * 获取用户信息，不展示当前用户
     * @return
     */
    @GetMapping
    public Result list() {
        return Result.ok("查询成功", userService.listWithRole(true, null));
    }

    @GetMapping("/{keywords}")
    public Result list(@PathVariable String keywords) {
        return Result.ok("查询成功", userService.listWithRole(true, keywords));
    }

    @PostMapping
    public Result addUser(@RequestBody BaseUser user) {
        return Result.ok("新增成功");
    }

    @PutMapping
    public Result updateUser(@RequestBody BaseUser user) {
        boolean flag = false;
        try{
            flag = userService.updateById(user);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        return flag ? Result.ok("更新成功"): Result.error("更新失败！");
    }

    @DeleteMapping("/{userId}")
    public Result deleteByUserId(@PathVariable Integer userId) {
        return userService.deleteByUserId(userId);
    }

    @DeleteMapping("/batch")
    public Result deleteBatch(@RequestBody NasDeleteListForm form) {
        List<Integer> idList = form.getIdList();
        boolean flag = userService.removeByIds(idList);
        return flag ? Result.ok("批量删除成功!"): Result.error("批量删除失败！");
    }


    @PutMapping("/authorise")
    public Result userAuthorise(@RequestBody BaseUserRoleEditForm form) {
        boolean flag = userService.userAuthorise(form.getUserId(), form.getRoleIdList());
        return flag? Result.ok("用户授权成功！") : Result.error("用户授权失败！");
    }
}
